<template>
  <el-page-header @back="goBack">
    <template #content>
      <span class="text-large font-600 mr-3">我的购物车</span>
    </template>
  </el-page-header>


  <div class="address-container">
    <el-form-item label="选择地址:" class="addr">
      <el-select v-model="selectedAddress" placeholder="请选择地址" style="width: 240px" @change="updateSubcategoryOptions">
        <el-option
            v-for="item in addressOptions"
            :key="item.id"
            :label="item.useraddress"
            :value="item.useraddress"
        />
      </el-select>
    </el-form-item>
    <el-button type="primary" class="add-address-btn">添加地址</el-button>

  </div>


  <el-table  :data="filteredCartItems" style="width: 100%" @selection-change="handleSelectionChange">
    <el-table-column
        type="selection"
        width="55">
    </el-table-column>
    <el-table-column prop="drugname" label="药品名称" width="150" />
    <el-table-column prop="drugprice" label="药品单价" width="120" />
    <el-table-column prop="drugnumber" label="数量" width="120" />
    <el-table-column fixed="right" label="操作" min-width="120">
      <template #default="scope">
        <el-button type="warning" size="default" @click="removeFromCart(scope.row.id)">
          移除
        </el-button>
      </template>
    </el-table-column>
  </el-table>

    <!-- 总计和结算按钮 -->
    <div class="total">
      总计：￥{{ totalAmount }}
    </div>
    <el-button type="danger" class="checkout-button" @click="checkout">去结算</el-button>

</template>

<script>
import axios from "axios";
import {ElMessage} from "element-plus";

export default {
  name: "ShopCar",
  data() {
    return {
      form: {},
      selectedAddress: '',
      addressOptions: [],
      cartItems: [],
      selectedItems: [],
      totalAmount: 0
    };
  },
  mounted() {
    this.getShopcar();
    this.getAddress();
    this.calculateTotal();
  },
  computed: {
    filteredCartItems() {
      return this.cartItems.filter(item => item.status === 1);
    }
  },
  methods: {

    getShopcar() {
      let userId = localStorage.getItem("userId");
      axios.get(`http://localhost:9099/cart/select?id=${userId}`).then(res => {
        this.cartItems = res.data.data;
      }).catch(error => {
        console.error("请求失败", error);
      });
    },
    getAddress() {
      let userId = localStorage.getItem("userId");
      axios.get(`http://localhost:9099/user/address?id=${userId}`).then(res => {
        this.addressOptions = res.data.data
      }).catch(error => {
        console.error("请求失败", error);
      });
    },
    updateCartItemStatus(items) {
      const updateData = items.map(item => ({
        id: item.id,
        status: 0
      }));
      const config = {
        headers: {
          'Content-Type': 'application/json'
        }
      };
      axios.post('http://localhost:9099/cart/change', updateData, config)
          .then(res => {
            if (res.data.code == 200) {
              this.getShopcar();
            } else {
              ElMessage({
                message: res.data.msg,
                type: 'error',
                duration: 2000
              });
            }
          })
          .catch(error => {
            console.error("更新状态请求失败", error);
            ElMessage.error("更新状态请求失败");
          });
    },

    goBack() {},
    removeFromCart(carid) {
      axios.get(`http://localhost:9099/cart/delete?id=${carid}`).then(res=> {
        if (res.data.code == 200) {
          ElMessage({
            message: res.data.msg,
            type: 'success',
            duration: 2000
          })
          window.location.reload(); // 刷新页面
        } else {
          ElMessage({
            message: res.data.msg,
            type: 'error',
            duration: 2000
          })
        }
      })

    },
    handleSelectionChange(selection) {
      this.selectedItems = selection;
      this.calculateTotal();
    },
    calculateTotal() {
      this.totalAmount = this.selectedItems.reduce((total, item) => {
        return total + (item.drugnumber * item.drugprice);
      }, 0);
    },
    checkout() {
      // 检查是否选择了地址
      if (!this.selectedAddress) {
        this.$message({
          message: '请选择收货地址',
          type: 'warning',
        });
        return;
      }

      // 检查是否选择了商品
      if (this.selectedItems.length === 0) {
        this.$message({
          message: '请选择要购买的商品',
          type: 'warning',
        });
        return;
      }

      const orderData = {
        billnum: this.generateBillNum(), // 订单编号
        address: this.selectedAddress,   // 收货地址
        productname: this.selectedItems.map(item => item.drugname).join(', '), // 商品名称拼接
        quantity: 1, // 商品数量，这里假设每个商品只购买一件
        ordertime : new Date().toISOString(),
        totalprice: this.totalAmount,      // 商品总价
        status: 1,                         // 订单状态，假设1代表待付款状态
        userid: parseInt(localStorage.getItem("userId"), 10), // 用户ID
      };

      // 设置请求头，确保Content-Type为application/json
      const config = {
        headers: {
          'Content-Type': 'application/json'
        }
      };
      // 发送请求到后端创建订单
      axios.post('http://localhost:9099/order/add', orderData,config)
          .then(res => {
            if (res.data.code == 200) {
              ElMessage({
                message: res.data.msg,
                type: 'success',
                duration: 2000
              })
              this.getShopcar();
              this.updateCartItemStatus(this.selectedItems);
              this.$router.push('/HomePage/OrderPage')
            } else {
              ElMessage({
                message: res.data.msg,
                type: 'error',
                duration: 2000
              })
            }
          })
          .catch(error => {
            console.error('创建订单请求失败', error);
            this.$message.error('创建订单请求失败');
          });
    },

    generateBillNum() {
      // 获取用户ID
      const userId = localStorage.getItem("userId");
      // 获取当前时间戳
      const timestamp = new Date().getTime();
      // 生成一个随机数，这里使用时间戳的后几位，确保随机性
      const randomNumber = timestamp % 10000; // 生成一个4位数的随机数

      // 组合用户ID和随机数生成订单编号
      return `${userId}_${randomNumber}`;
    }
  }
};
</script>

<style scoped>


.total {
  text-align: left; /* 使文本靠左对齐 */
  font-weight: bold;
  font-size: 1.2em; /* 根据需要调整字体大小 */
}

.checkout-button {
  margin-top: 10px;
  display: block; /* 使按钮独占一行 */
}
.addr{
  margin-top: 20px;
}
.address-container {
  display: flex;
  align-items: center; /* 垂直居中 */
  gap: 10px; /* 根据需要调整间距 */
}

.addr .el-form-item__content {
  flex: 1; /* 让选择框占据剩余空间 */
  margin-right: 10px; /* 与按钮之间的间距 */
}

.add-address-btn {
  /* 根据需要添加按钮样式 */
}
</style>